<?php

declare (strict_types = 1);

namespace app\certificate\controller\admin\v1\risk;

use libs\ALiOss;
use libs\Image;
use think\facade\Db;
use think\Request;

class Type
{
    /**
     * @Description:
     * @Author: Terry
     * @Date: 2024-01-31 16:41:47
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'];
        $page  = $data['page'];
        $where = [
            ['rt.projectCode', '=', $request->authWhere['projectCode']],
            ['rt.isDelete', '=', $data['status']],
        ];
        if (!empty($data['name'])) {
            array_push($where, ['rt.name', 'like', "%" . $data['name'] . "%"]);
        }

        //判断身份
        if (isset($request->authWhere['corpCode'])) {
            array_push($where, ['rt.corpCode', '=', $request->authWhere['corpCode']]);
        } elseif (!empty($data['corpCode'])) {
            array_push($where, ['rt.corpCode', '=', $data['corpCode']]);
        }

        $list = DB::table('certificate_riskType')
            ->alias('rt')
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['rt.inDate', 'rt.corpCode', 'rt.name', 'rt.remark', 'rt.uuid', 'rt.qrCode', 'rt.expiredTime', 'rt.formUuid', 'rt.subtitle'])
            ->order(['rt.id desc'])
            ->select()->toArray();

        foreach ($list as $key => $value) {
            $list[$key]['isAuditNums'] = DB::table('certificate_riskTypeAuth')->where('typeUuid', $value['uuid'])->where('isAudit', 1)->count();
        }

        $count = DB::table('certificate_riskType')
            ->alias('rt')
            ->where($where)
            ->count('rt.id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 添加
     * @Author: Terry
     * @Date: 2024-01-31 21:02:21
     * @param {Request} $requestdestroyde
     */
    public function create(Request $request)
    {
        $prjCode             = $request->prjCode;
        $data                = $request->data;
        $data['uuid']        = createUuid();
        $data['projectCode'] = $request->prjCode;
        $projectName         = DB::table('projectInfo')->where(['code' => $request->prjCode])->value('name', '-');
        DB::startTrans();
        try {
            //添加许可证
            $text           = $projectName . '\n(工作許可證)' . $data['name'];
            $data['qrCode'] = $this->qrCode($request->prjCode, $data['uuid'], $text);
            DB::table('certificate_riskType')->insert($data);
            DB::commit();
            $data['inDate']   = date('Y-m-d', $_SERVER['REQUEST_TIME']);
            $data['formUuid'] = '';
            return result(SUCCESS, $data, '添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
        }
        return result(FAIL, '', '添加失败,请重试');
    }
    /**
     * @Description: 修改
     */
    public function update(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['uuid'];
        $cehck = DB::table('certificate_riskType')->where([
            ['uuid', '<>', $uuid],
            ['name', '=', $data['name']],
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->prjCode],
        ])->value('id');
        if ($cehck) {
            return result(FAIL, '', '名称已存在,无法修改!');
        }

        $oldName = DB::table('certificate_riskType')->where([
            ['uuid', '=', $uuid],
            ['isDelete', '=', 0],
        ])->value('name');
        if (!$oldName) {
            return result(FAIL, '', '类型已被删除无法修改!');
        }

        $updateData = [
            'name'     => $data['name'],
            'remark'   => $data['remark'] ?? '',
            'subtitle' => $data['subtitle'],
            'corpCode' => $data['corpCode'],
            'flowUuid' => $data['flowUuid'] ?? '',
        ];
        $return = [];
        if ($data['name'] != $oldName) {
            $projectName          = DB::table('projectInfo')->where(['code' => $request->prjCode])->value('name', '-');
            $text                 = $projectName . '\n(工作許可證)' . $data['name'];
            $updateData['qrCode'] = $this->qrCode($request->prjCode, $data['uuid'], $text);
            $return               = ['qrCode' => $updateData['qrCode']];
        }
        DB::table('certificate_riskType')->where('uuid', $uuid)->update($updateData);
        return result(SUCCESS, $return, '保存成功');
    }

    public function destroy(Request $request)
    {
        $data = $request->data;
        DB::table('certificate_riskType')->where('uuid', $data['uuid'])->update([
            'isDelete' => 1,
        ]);
        return result(SUCCESS, '', '删除成功');
    }

    /**
     * @Description: 获取字典
     * @Author: Terry
     * @Date: 2024-01-31 22:37:41
     * @param {Request} $request
     */
    public function getOptions(Request $request)
    {
        $data['corp'] = DB::table('projectInfo_projectCorpInfo')
            ->where([
                ['entryTime', '<>', '0000-00-00 00:00:00'],
                ['projectCode', '=', $request->prjCode],
            ])
            ->order('exitTime')
            ->group('corpCode')
            ->field(['corpName', 'corpCode'])
            ->select()->toArray();

        return result(SUCCESS, $data, '');
    }

    /**
     * @Descripttion:二维码生成
     * @name: qrCode
     * @Author: Terry
     * @Date: 2021-04-01 22:21:14
     * @param {*} $uuid
     */
    private function qrCode($prjCode, $uuid, $text)
    {
        $file   = "image/qrcode/{$prjCode}";
        $name   = time() . rand(0, 99999) . '.jpg';
        $path   = "packageC/pages/certificate/worker/apply/apply?uuid={$uuid}";
        $qrCode = createQrCode($path, $name, $file);
        if (!$qrCode) {
            return false;
        }

        $img  = new image();
        $path = $img->imgButtomAddText($qrCode, $text);

        $exp  = explode('.', $path);
        $oss  = new ALIOss($exp[0], $exp[1]);
        $path = $oss->upload($path);

        return $path;
    }

    /**
     * @Description: 获取数据
     * @param {Request} $request
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $data = DB::table('certificate_riskType')->where('uuid', $uuid)->field(['inDate', 'corpCode', 'name', 'remark', 'uuid', 'qrCode', 'type', 'expiredTime', 'duration', 'formUuid', 'exitFormUuid'])->find();

        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 获取人员类型权限列表
     * @param {Request} $request
     */
    public function getWorkerAuthList(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
            ['entryTime', '<>', '0000-00-00 00:00:00'],
            ['exitTime', '=', '0000-00-00 00:00:00'],
        ];

        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['pw.corpCode', '=', $request->corpCode]);
        }

        $lists = DB::table('certification_projectWorker')
            ->where($where)
            ->where($request->authWhere)
            ->field(['teamName', 'workerName', 'teamSysNo', 'wxappUserUuid', 'corpName', 'corpCode'])
            ->group(['wxappUserUuid', 'corpCode'])
            ->select()->toArray();
        foreach ($lists as &$value) {
            if (empty($value['workerName'])) {
                $value['workerName'] = DB::table('platform_wxappUser')->where('wxappUserUuid', $value['wxappUserUuid'])->value('nickName');
            }
            $formAuth = DB::table('certificate_riskTypeAuth')
                ->where(['typeUuid' => $data['uuid'], 'isDelete' => 0, 'wxappUserUuid' => $value['wxappUserUuid']])
                ->field('isAudit')
                ->find();
            if (!$formAuth) {
                $formAuth = ['isAudit' => 0];
            }

            $value = array_merge($value, $formAuth);
        }
        $list    = $this->centerProcess($lists);
        $checked = DB::table('certificate_riskTypeAuth')
            ->where(['typeUuid' => $data['uuid'], 'isDelete' => 0])
            ->column('wxappUserUuid');
        $data = compact('list', 'checked');

        return result(SUCCESS, $data, '');
    }
    //人员分类信息
    private function centerProcess($data)
    {
        if (!$data) {
            return $data;
        }

        $arr = [];
        foreach ($data as $key => $value) {
            if (empty($value['workerName'])) {
                $wxappUserData = DB::table('platform_wxappUser')->where('wxappUserUuid', $value['value'])->field(['nickName'])->findOrEmpty();

                if (empty($wxappUserData)) {
                    continue;
                }

                $value['workerName']    = $wxappUserData['nickName'];
                $value['hasWorkerInfo'] = 0;
            }
            $data = [
                'value'    => $value['wxappUserUuid'],
                'name'     => $value['workerName'],
                'corpCode' => $value['corpCode'],
                'isAudit'  => $value['isAudit'],
            ];
            $arr[$value['corpCode']]['name']                                        = $value['corpName'];
            $arr[$value['corpCode']]['children'][$value['teamSysNo']]['name']       = $value['teamName'];
            $arr[$value['corpCode']]['children'][$value['teamSysNo']]['children'][] = $data;
        }
        sort($arr);
        foreach ($arr as $key => $value) {
            if (isset($value['children'])) {
                sort($value['children']);
                $arr[$key]['children'] = $value['children'];
            }
        }
        return $arr;
    }

    /**
     * @Description: 修改管理人员权限
     * @param {Request} $request
     */
    public function changeWorkerAuth(Request $request)
    {
        $data     = $request->data;
        $typeUuid = $data['uuid'];

        $globalData = dataMerge($request->uuid, [
            'typeUuid' => $typeUuid,
        ]);

        DB::startTrans();
        try {
            DB::table('certificate_riskTypeAuth')
                ->where([
                    'typeUuid' => $typeUuid,
                ])
                ->delete();
            $create = $data['value'];
            if ($create) {
                foreach ($create as $key => $value) {
                    $insertData[] = array_merge(['wxappUserUuid' => $value['wxappUserUuid'], 'uuid' => createUuid(), 'isAudit' => isset($value['isAudit']) ? $value['isAudit'] : 0], $globalData);
                }
                DB::table('certificate_riskTypeAuth')->insertAll($insertData);
            }
            DB::commit();
            return result(SUCCESS, '', '更新成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return result(FAIL, '', '更新失败');
        }
    }
}
